import koa from 'koa'
import Router from 'koa-router'
import bodyparser from 'koa-bodyparser'
import cors from '@koa/cors'
import { Sequelize,DataTypes,Op, or } from 'sequelize'

const app = new koa()
const router = new Router()






 let sequelize = new Sequelize('aaa','root','123456',{
    dialect:'mysql',
    host:'localhost'

})
let Book = sequelize.define('books',{
    booksName:DataTypes.STRING,
    author:DataTypes.STRING,

})

// await sequelize.sync();

// Book.bulkCreate([
//     {
//         booksName: '剑来',
//         author:'1'
//     },
//     {
//         booksName: '斗罗大陆',
//         author:'2'

//     },
// ])


app.use(cors())
app.use(bodyparser())


router.get('/books',async (ctx)=>{
    let res
    let keyword = ctx.request.query.keyword ||''
    if(keyword){
        res =await Book.findAll({
            where:{
                [Op.or]:{
                    booksName:{
                        [Op.like]:`%${keyword}%`
                    }
                }
            }
        })
    }else{
        res =await Book.findAll();
    }
   
    ctx.body={
        code:1000,
        data:res,
        msg:'成功'

    }
})

router.post('/books',async (ctx) =>{
    let obj =ctx.request.body;
    let res = await Book.create(obj)
    ctx.body={
        code:1000,
        data:res,
        msg:'新增'
    }
})

router.put('/books/:id',async(ctx)=>{
    let id =ctx.params.id ||0
    let obj = ctx.request.body
    let res = await Book.update(obj,{
        where:{
            id
        }
    })
    ctx.body={
        code:1000,
        data:res,
        msg:'修改'
    }
})

router.delete('/books/:id',async(ctx)=>{
    let id =ctx.params.id || 0
    let res = await Book.destroy({
        where:{
            id
        }
    })
    ctx.body={
        code:1000,
        data:res,
        msg:'删除'
    }
})
router.get('/books/:id',async(ctx)=>{
    let id = ctx.params.id ||0
    let res = await Book.findByPk(id)
    ctx.body={
        code:1000,
        data:res,
        msg:'指定'
    }
})

app.use(router.routes())



let appPost = 4000
app.listen(appPost)
console.log(`http://localhost${appPost}`);
